<template>
    <div class="order-report">
        <div class="report-table-top-title" style="height: 50px">
            应用包创建
            <span
                style="color: #000; font-size: 15px; margin-left: 20px"
            ></span>
            <span style="float: right">
                <el-button type="primary" plain size="small" @click="save"
                    >确认保存</el-button
                >
                <el-button
                    type="danger"
                    plain
                    size="small"
                    @click="$emit('save')"
                    >返回</el-button
                >
            </span>
        </div>
        <!-- 表单主体 -->
        <div class="report-table-form1">
            <el-form
                style="width: 750px"
                @submit.native.prevent
                ref="form"
                :model="form"
                :rules="rules"
                size="small"
                label-width="150px"
            >
                <el-form-item label="设备类型：" >
                    <el-select
                        class="items"
                        v-model="terminalTypeName"
                        filterable
                        placeholder="请选择"
                        size="small"
                        :disabled='status === 1 ? true:false'
                    >
                        <el-option
                            v-for="(item, index) in terminalTypeList"
                            :key="index"
                            :label="item.terminalTypeName"
                            :value="item.terminalTypeName"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item
                    label="应用包类型："
                    
                >
                    <el-select
                        class="items"
                        v-model="appPackageTypeName"
                        filterable
                        placeholder="请选择"
                        size="small"
                    >
                        <el-option
                            v-for="(item, index) in packageFileTypeList"
                            :key="index"
                            :label="item.appPackageTypeName"
                            :value="item.appPackageTypeName"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="应用包名称：" prop="packageName">
                    <el-input
                        placeholder="应用包名称，包括后缀名"
                        size="small"
                        v-model="form.packageName"
                        :disabled='status === 1 ? true:false'
                    ></el-input>
                </el-form-item>
                <el-form-item label="应用包作者：" prop="auther">
                    <el-input
                        placeholder="应用包作者"
                        size="small"
                        v-model="form.auther"
                    ></el-input>
                </el-form-item>
                <el-form-item label="应用包：" prop="packageUrl">
                    <div style="width: 100%" class="column left">
                        <el-upload
                            class="upload-demo"
                            action
                            :on-remove="handleRemove"
                            :limit="1"
                            ref="upload"
                            :http-request="(e)=>{fnUploadRequest(e,0)}"
                            :file-list="fileList"
                        >
                            <el-button
                                @click="$refs.upload.clearFiles()"
                                size="small"
                                type="primary"
                                >点击上传应用包</el-button
                            >
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="应用包 URL：" prop="packageUrl">
                    <el-input
                        size="small"
                        disabled
                        placeholder="上传后自动生成"
                        v-model="form.packageUrl"
                    ></el-input>
                </el-form-item>
                <el-form-item label="应用包大小(Mb)：" prop="packageSize">
                    <el-input
                        disabled
                        size="small"
                        placeholder="上传后自动生成"
                        v-model="form.packageSize"
                    ></el-input>
                </el-form-item>
                <el-form-item label="md5：" prop="md5">
                    <el-input
                        size="small"
                        placeholder="请输入md5"
                        max="32"
                        v-model="form.md5"
                    ></el-input>
                </el-form-item>
                <el-form-item label="应用包版本号：" prop="packageVersionCode">
                    <el-input
                        size="small"
                        placeholder="请输入版本号"
                        v-model="form.packageVersionCode"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="内部版本号："
                    prop="internalPackageVersionCode"
                >
                    <el-input
                        size="small"
                        placeholder="请输入内部版本号"
                        v-model="form.internalPackageVersionCode"
                    ></el-input>
                </el-form-item>
                <el-form-item label="应用包介绍图片地址：" prop="introducePicUrl">
                    <el-upload
                            class="upload-demo"
                            action
                            :on-remove="handlePicRemove"
                            :limit="1"
                            :http-request="(e)=>{fnUploadRequest(e,1)}"
                            :file-list="picList"
                            list-type="picture"
                        >
                            <el-button
                                size="small"
                                type="primary"
                                >点击上传介绍图</el-button
                            >
                        </el-upload>
                </el-form-item>
                <el-form-item
                    label="应用包简介文本："
                    prop="introduceText"
                >
                <textarea v-model="form.introduceText" id="" cols="30" rows="10"></textarea>
                </el-form-item>
                <el-form-item
                    label="备注："
                    prop="remarks"
                >
                <textarea v-model="form.remarks" id="" cols="30" rows="10"></textarea>
                </el-form-item>
                <el-form-item>
                    <div class="center">
                        <el-button type="primary" size="small" @click="save"
                            >确认保存</el-button
                        >
                        <el-button
                            type="danger"
                            plain
                            size="small"
                            @click="$emit('save')"
                            >返回</el-button
                        >
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
import OSS from 'ali-oss'
import TinymceEditor from '@/common/Tinymce'
export default {
    props: {
        row: Object
    },
    components: {
        TinymceEditor
    },
    data: function () {
        return {
            zdList: [],
            yesOrNoList: [
                { name: '是', value: 1 },
                { name: '否', value: 0 }
            ],
            upgradeModelList: [
                { name: '设备模式', value: 1 },
                { name: '场所模式', value: 0 }
            ],
            packageFileTypeList: [],
            terminalTypeList: [],
            appPackageTypeName: '',
            terminalTypeName: '',
            typeList: [],
            fileList: [],
            picList: [],
            form: {
                packageName: '', // 应用包名称
                packageUrl: '', // 应用包下载地址
                packageFileName: '', // 应用包文件名称
                packageSize: '', // 应用包文件大小
                terminalType: '', // 设备类型
                md5: '', // md5
                packageVersionCode: '', // 应用包版本号
                internalPackageVersionCode: '', // 应用包内部版本号
                introduceText: '', // 应用包简介文本
                introducePicUrl: '', // 应用包介绍图片地址
                appPackageType: '', // 应用包类型
                auther: '', // 应用包作者
                remarks: '' // 备注
            },
            status: 0, // 判断编辑还是新增入口进入 1编辑 0新增
            rules: {
                packageName: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                terminalTypeName: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                packageUrl: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                packageFileName: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                packageSize: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                md5: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                packageVersionCode: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                internalPackageVersionCode: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                introduceText: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                introducePicUrl: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
                appPackageTypeName: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                auther: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ],
                remarks: [
                    { required: true, message: '不能为空', trigger: 'change' }
                ]
            }
        }
    },
    watch: {
        'form.internalDescription' (newValue, oldValue) {
            console.log(newValue)
            this.$refs.form.validateField('internalDescription')
        },
        'form.externalDescription' (newValue, oldValue) {
            this.$refs.form.validateField('externalDescription')
        }
    },
    mounted () {
        this.status = this.row.appPackageID ? 1 : 0
    },
    created () {
        this.getUpgradePackageFileType()
        this.getTerminalTypeByType()
        if (this.row.appPackageID) {
            this.form = this.copyArr(this.row)
            this.fileList = [
                {
                    name: this.form.packageFileName,
                    url: this.form.packageUrl
                }
            ]
            this.picList = [
                {
                    name: '',
                    url: this.form.introducePicUrl
                }
            ]
        }
    },
    methods: {
        changeForm (e, name) {
            this.$refs.form.validateField(name)
        },
        getUpgradePackageFileType () {
            this.$http.get(this.$store.state.IP + '/appStore/appPackageTypeEnum', {
            },
                {
                    'emulateJSON': false
                }
            ).then(response => {
                console.log('-------------------------------------------')
                response = response.body
                console.log(response)
                if (response.ret === '0') {
                    this.packageFileTypeList = response.res
                }
            }, response => {
            })
        },
        getTerminalTypeByType () {
            this.$http.get(this.$store.state.IP + '/appStore/terminalTypeEnum',
                {
                    'emulateJSON': false
                }
            ).then(response => {
                console.log('-------------------------------------------')
                response = response.body
                console.log(response)
                if (response.ret === '0') {
                    this.terminalTypeList = response.res
                    if (this.status === 1) {
                         this.terminalTypeList.forEach(item => {
                            if (item.terminalTypeValue === this.form.terminalType) {
                                this.terminalTypeName = item.terminalTypeName
                             }
                         })
                         this.appPackageTypeName = this.form.appPackageTypeName
                    }
                }
            }, response => {
            })
        },
        handleRemove (file) {
            console.log(file)
            this.form.packageUrl = ''
            this.form.packageFileName = ''
            this.form.packageSize = ''
            this.fileList = []
        },
        handlePicRemove (file) {
            console.log(file)
            this.form.introducePicUrl = ''
            this.picList = []
        },
        async getOssParms () {
            console.log()
            let params = {
                params: {}
            }
            let ret = await this.$http
                .get(
                    this.$store.state.IP +
                    '/oss/getAuthorizationInfo?path=skinPackage',
                    params
                )
            return ret.body.data
        },
        async fnUploadRequest (option, status) {
            try {
                let vm = this
                // 获取OSS配置信息
                let val = await vm.getOssParms()
                let filename = val.path + '/' + Date.parse(new Date()) + '.zip'
                let client = new OSS({
                    region: val.region,
                    accessKeyId: val.accessKeyId,
                    accessKeySecret: val.accessKeySecret,
                    secure: false,
                    bucket: val.bucket,
                    stsToken: val.securityToken
                })
                let currentCheckpoint = 0
                let retryCount = 0
                const retryCountMax = 10
                let file = option.file

                const uploadFile = function uploadFile () {
                    const options = {
                        progress: async function (p, checkpoint) {
                            currentCheckpoint = checkpoint
                            let e = {}
                            e.percent = p * 100
                            option.onProgress(e)
                        },
                        partSize: 1000 * 1024,
                        meta: {
                            year: 2021,
                            people: 'test'
                        },
                        timeout: 60000
                    }

                    if (currentCheckpoint) {
                        options.checkpoint = currentCheckpoint
                    }
                    client
                        .multipartUpload(filename, file, options)
                        .then((res) => {
                            res = res.res
                            console.log('upload success: %j', res)
                            currentCheckpoint = null
                            let indexID = res.requestUrls[0].indexOf('?uploadId')
                            if (indexID !== -1) {
                                res.requestUrls[0] = res.requestUrls[0].substring(0, indexID)
                            }
                            console.log(res.requestUrls[0])
                            if (status === 0) {
                                vm.form.packageUrl = res.requestUrls[0]
                                vm.form.packageFileName = option.file.name
                                vm.form.packageSize = (option.file.size / 1024 / 1024).toFixed(2)
                            } else {
                                vm.form.introducePicUrl = res.requestUrls[0]
                            }
                            option.onSuccess(res)
                        })
                        .catch((err) => {
                            if (client && client.isCancel()) {
                            } else {
                                console.log(`err.name : ${err.name}`)
                                console.log(`err.message : ${err.message}`)
                                // timeout retry
                                if (retryCount < retryCountMax) {
                                    retryCount++
                                    console.error(`retryCount : ${retryCount}`)
                                    uploadFile()
                                } else {
                                    console.error(err)
                                    this.disabled = false
                                    this.$error(err.message)
                                }
                            }
                        })
                }
                uploadFile()
            } catch (error) {
                console.error(error)
                this.disabled = false
                this.$error(error.message)
            }
        },
        // 保存表单
        save () {
             this.terminalTypeList.forEach(item => {
                if (item.terminalTypeName === this.terminalTypeName) {
                    this.form.terminalType = item.terminalTypeValue
                }
            })
            this.packageFileTypeList.forEach(item => {
                if (item.appPackageTypeName === this.appPackageTypeName) {
                    this.form.appPackageType = item.appPackageType
                }
            })
            if (this.status === 0) this.addForm()
            if (this.status === 1) this.editForm()
        },
        addForm () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading = true
                    this.$http.post(this.$store.state.IP + '/appStore/addAppPackage', {
                        ...this.form
                    },
                        {
                            'emulateJSON': false
                        }
                    ).then(response => {
                        console.log('-------------------------------------------')
                        response = response.body
                        console.log(response)
                        if (response.ret === '0') {
                            this.$message({
                                message: '保存成功',
                                type: 'success'
                            })
                            this.$emit('save')
                            this.loading = false
                        } else {
                            this.loading = false
                        }
                    }, response => {
                        this.loading = false
                        console.log('通讯失败')
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        editForm () {
            delete this.form.created
            delete this.form.upgradeTime
            delete this.form.appPackageTypeName
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading = true
                    this.$http.post(this.$store.state.IP + '/appStore/alterAppPackage', {
                        ...this.form
                    },
                        {
                            'emulateJSON': false
                        }
                    ).then(response => {
                        console.log('-------------------------------------------')
                        response = response.body
                        console.log(response)
                        if (response.ret === '0') {
                            this.$message({
                                message: '保存成功',
                                type: 'success'
                            })
                            this.$emit('save')
                            this.loading = false
                        } else {
                            this.loading = false
                        }
                    }, response => {
                        this.loading = false
                        console.log('通讯失败')
                    })
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        }
    }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.avatar-uploader .el-upload
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden

.avatar-uploader .el-upload:hover
    border-color: #409EFF

.avatar-uploader-icon
    font-size: 28px
    color: #8c939d
    width: 178px
    height: 178px
    line-height: 178px
    text-align: center

.avatar
    width: 178px
    height: 178px
    display: block

.report-table-form1
    width: 100%
    min-height: 40px
    padding: 50px 20px
    box-sizing: border-box
    background: #fff
    overflow: hidden
    display: flex
    justify-content: center

.report-table-top-title
    width: 100%
    height: 64px
    line-height: 64px
    color: #000
    font-size: 18px

.order-report-agent
    width: 100%
    background: #f1f0f5

    .el-transfer__button:first-child
        display: none

    .report-table-block
        width: 100%
        padding-top: 22px
        height: 50px
        background: #fff
        box-sizing: border-box

        .report-table-block-in
            float: right
            padding-right: 17px

    .page-padding-gray-small
        width: 100%
        height: 22px
        background: #f1f0f5

    .page-padding
        width: 100%
        height: 20px
        background: #fff

    .report-table-total
        width: 100%
        font-size: 16px
        color: #409EFF
        padding: 22px
        margin-top: 22px
        box-sizing: border-box
        background: #fff

.items
    width: 100%

.center
    text-align: center

.flex
    display: flex
    align-items: center
</style>
